package cn.qj.ymcc.service.impl;

import cn.qj.ymcc.constants.BusinessConstants;
import cn.qj.ymcc.dto.CodeDto;
import cn.qj.ymcc.service.VerifyCodeService;
import cn.qj.ymcc.util.SendSmsUtil;
import cn.qj.ymcc.util.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class VerifyCodeImpl implements VerifyCodeService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    //发送短信验证码
    @Override
    public void sendSmsCode(String phone) {

        //校验 正则 phone不为空

        if(StringUtils.isEmpty(phone)){
            throw new RuntimeException("手机号不能为空");
        }
        //key
        String key = BusinessConstants.PHONE_REGISTER + phone;
        //从redis查到value
        Object obj = redisTemplate.opsForValue().get(key);
        CodeDto value = null;
        //如果value不为空，说明手机号已经发送过验证码了
        if(obj != null){
            value = (CodeDto) obj;
            String code = value.getCode();
            //当前时间-上次发送时间 < 60s
            if(new Date().getTime() - value.getTimer() < 60000){
                throw new RuntimeException("请勿重复发送验证码");
            }
        }else{
            //如果value为空，说明手机号没有发送过验证码
            //生成验证码
            String code = VerifyCodeUtils.generateVerifyCode(4);

            //value:{验证码+timer}
            long time = new Date().getTime();
            //这个就是value值
            value = new CodeDto(code,time);

        }
        log.info("手机号{}已经发送过验证码了，验证码是{},请在{}分钟之内使用",phone,value.getCode(),5);
        //发送短信
        //SendSmsUtil.sendSms(phone,value.getCode());
        redisTemplate.opsForValue().set(key,value,5, TimeUnit.MINUTES);
    }
}
